package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.db.DBManager;
import com.example.myapplication.model.Course;
import com.example.myapplication.model.Teacher;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText searchEditText;
    private ImageButton searchButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("主页");
            getSupportActionBar().setElevation(4); // 添加阴影效果
        }

        // 设置状态栏和导航栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 设置状态栏为透明
        getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);

        // 初始化视图
        searchEditText = findViewById(R.id.editTextSearch);
        searchButton = findViewById(R.id.buttonSearch);

        // 初始化讲座按钮
        View btnLecture = findViewById(R.id.btnLecture);
        if (btnLecture != null) {
            btnLecture.setOnClickListener(this);
        }
        // 初始化录入老师任课按钮
        View btnAddTeacherCourse = findViewById(R.id.btnAddTeacherCourse);
        if (btnAddTeacherCourse != null) {
            btnAddTeacherCourse.setOnClickListener(this);
        }

        // 设置搜索框的回车键监听
        searchEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH ||
                    actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE ||
                    event != null && event.getAction() == android.view.KeyEvent.ACTION_DOWN &&
                            event.getKeyCode() == android.view.KeyEvent.KEYCODE_ENTER) {
                performSearch();
                return true;
            }
            return false;
        });

        // 设置搜索按钮点击监听
        searchButton.setOnClickListener(v -> {
            String query = searchEditText.getText().toString().trim();
            if (query.isEmpty())
                return;

            // 显示加载进度
            View loadingView = findViewById(R.id.loadingProgress);
            if (loadingView != null) {
                loadingView.setVisibility(View.VISIBLE);
            } // 在后台线程执行数据库查询
            new Thread(() -> {
                try {
                    DBManager dbManager = new DBManager(MainActivity.this);
                    // 先查老师
                    ArrayList<Course> teacherCourses = dbManager.getCoursesByTeacherName(query);
                    ArrayList<Teacher> courseTeachers = dbManager.getTeachersByCourseName(query);

                    // 在主线程更新UI
                    runOnUiThread(() -> {
                        if (loadingView != null) {
                            loadingView.setVisibility(View.GONE);
                        }

                        try {
                            if (!teacherCourses.isEmpty()) {
                                Intent intent = new Intent(MainActivity.this, CourseListActivity.class);
                                intent.putExtra("teacherName", query);
                                startActivity(intent);
                            } else if (!courseTeachers.isEmpty()) {
                                Intent intent = new Intent(MainActivity.this, TeacherListActivity.class);
                                intent.putExtra("courseName", query);
                                startActivity(intent);
                            } else {
                                // 没有找到
                                Toast.makeText(MainActivity.this, "未找到相关课程或教师", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "打开页面失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    runOnUiThread(() -> {
                        if (loadingView != null) {
                            loadingView.setVisibility(View.GONE);
                        }
                        Toast.makeText(MainActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }).start();
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnLecture) {
            Intent intent = new Intent(this, LectureActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.btnAddTeacherCourse) {
            Intent intent = new Intent(this, AddTeacherCourseActivity.class);
            startActivity(intent);
        }
    }

    private void performSearch() {
        String query = searchEditText.getText().toString().trim();
        if (query.isEmpty()) {
            Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载进度
        View loadingView = findViewById(R.id.loadingProgress);
        if (loadingView != null) {
            loadingView.setVisibility(View.VISIBLE);
        }

        // 在后台线程执行数据库查询
        new Thread(() -> {
            try {
                DBManager dbManager = new DBManager(MainActivity.this);
                
                // 检查数据库状态
                dbManager.checkDatabaseState();
                
                // 先查老师
                ArrayList<Course> teacherCourses = dbManager.getCoursesByTeacherName(query);
                ArrayList<Teacher> courseTeachers = dbManager.getTeachersByCourseName(query);

                // 在主线程更新UI
                runOnUiThread(() -> {
                    try {
                        if (loadingView != null) {
                            loadingView.setVisibility(View.GONE);
                        }

                        if (teacherCourses != null && !teacherCourses.isEmpty()) {
                            Intent intent = new Intent(MainActivity.this, CourseListActivity.class);
                            intent.putExtra("teacherName", query);
                            startActivity(intent);
                        } else if (courseTeachers != null && !courseTeachers.isEmpty()) {
                            Intent intent = new Intent(MainActivity.this, TeacherListActivity.class);
                            intent.putExtra("courseName", query);
                            startActivity(intent);
                        } else {
                            // 没有找到
                            Toast.makeText(MainActivity.this, "未找到相关课程或教师", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "页面跳转失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() -> {
                    if (loadingView != null) {
                        loadingView.setVisibility(View.GONE);
                    }
                    Toast.makeText(MainActivity.this, "搜索失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            // 获取状态栏高度并设置给占位View
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            }
            View statusBarBackground = findViewById(R.id.statusBarBackground);
            if (statusBarBackground != null) {
                statusBarBackground.getLayoutParams().height = statusBarHeight;
                statusBarBackground.requestLayout();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 0, "导出数据");
        menu.add(0, 2, 0, "导入数据");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            exportData();
            return true;
        } else if (item.getItemId() == 2) {
            importData();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void exportData() {
        try {
            DBManager dbManager = new DBManager(this);
            String jsonData = dbManager.exportData();
            
            // 将数据写入文件
            File backupFile = new File(getExternalFilesDir(null), "school_data_backup.json");
            FileWriter writer = new FileWriter(backupFile);
            writer.write(jsonData);
            writer.close();
            
            Toast.makeText(this, "数据已导出到: " + backupFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "导出数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void importData() {
        try {
            File backupFile = new File(getExternalFilesDir(null), "school_data_backup.json");
            if (!backupFile.exists()) {
                Toast.makeText(this, "未找到备份文件", Toast.LENGTH_SHORT).show();
                return;
            }

            // 读取JSON数据
            StringBuilder jsonData = new StringBuilder();
            BufferedReader reader = new BufferedReader(new FileReader(backupFile));
            String line;
            while ((line = reader.readLine()) != null) {
                jsonData.append(line);
            }
            reader.close();

            // 导入数据
            DBManager dbManager = new DBManager(this);
            boolean success = dbManager.importData(jsonData.toString());
            
            if (success) {
                Toast.makeText(this, "数据导入成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "数据导入失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "导入数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
